<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2019/11/28
 * Time: 16:57
 */

namespace app\common\model;

//rc4加密
class RivestCipher
{
    /**
     * @name 加密
     * @param $data
     * @return string
     * @author wx
     * @date 2019/11/28 17:02
     */
    public function encrypt($data)
    {
        //1. json化
        $jsonStr = json_encode($data);

        //2. base64加密
        $base64Str = base64_encode($jsonStr);
        
        //3. rc4加密
        $rc4Str = $this->rc4($base64Str);

        return $rc4Str;
    }

    /**
     * @name 解密
     * @param $data
     * @return mixed
     * @author wx
     * @date 2019/11/28 17:05
     */
    public function decrypt($data)
    {
        //1. 解密rc4
        $base64Str = $this->rc4($data);
        
        //2. base64解密
        $jsonStr = base64_decode($base64Str);

        //3. 反json
        $str = json_decode($jsonStr,true);

        return $str;
    }

    /**
     * @name rc4加密算法
     * @param $data
     * @return string
     * @author wx
     * @date 2019/11/28 16:58
     */
    private function rc4($data)
    {
        $pwd = 'evMuZXULGKaK48DupIhGhnOgqe2sYBJuNz7rz3vbcmGAtslwgh1COwC2GiRIaouOuiQSxamm8NO8U1s1jNNWuSwteOCnM3C6gHa';
        $cipher      = '';
        $key[]       = "";
        $box[]       = "";
        $pwd_length  = strlen($pwd);
        $data_length = strlen($data);
        for ($i = 0; $i < 256; $i++) {
            $key[$i] = ord($pwd[$i % $pwd_length]);
            $box[$i] = $i;
        }
        for ($j = $i = 0; $i < 256; $i++) {
            $j       = ($j + $box[$i] + $key[$i]) % 256;
            $tmp     = $box[$i];
            $box[$i] = $box[$j];
            $box[$j] = $tmp;
        }
        for ($a = $j = $i = 0; $i < $data_length; $i++) {
            $a       = ($a + 1) % 256;
            $j       = ($j + $box[$a]) % 256;
            $tmp     = $box[$a];
            $box[$a] = $box[$j];
            $box[$j] = $tmp;
            $k       = $box[(($box[$a] + $box[$j]) % 256)];
            $cipher .= chr(ord($data[$i]) ^ $k);
        }
        return $cipher;
    }
}